package com.agileai.bpm.controller.define;

import java.util.ArrayList;
import java.util.List;

import com.agileai.bpm.bizmoduler.define.WfProcessManage;
import com.agileai.bpm.model.DataFieldsDocument.DataFields;
import com.agileai.bpm.model.ProcessDefineDocument;
import com.agileai.bpm.model.VariableType;
import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.hotweb.controller.core.BaseHandler;
import com.agileai.hotweb.renders.LocalRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.util.StringUtil;

public class WfProcessVariableSelectHandler extends BaseHandler{
	public WfProcessVariableSelectHandler(){
		super();
	}
	
	public ViewRenderer prepareDisplay(DataParam param){
		String processId = param.get("WFP_ID");
		DataParam queryParam = new DataParam("WFP_ID",processId);
		WfProcessManage processManage = this.lookupService(WfProcessManage.class);
		DataRow row = processManage.getRecord(queryParam);
		String processDefineXML = row.getString("WFP_DEFINE");
		try {
			ProcessDefineDocument processDefineDocument = ProcessDefineDocument.Factory.parse(processDefineXML);
			DataFields dataFields = processDefineDocument.getProcessDefine().getDataFields();
			List<DataRow> processVars = null;
			if (dataFields != null){
				processVars = buildProcessVars(dataFields);
			}
			this.setRsList(processVars);
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
		return new LocalRenderer(getPage());
	}
	
	private List<DataRow> buildProcessVars(DataFields dataFields){
		List<DataRow> result = new ArrayList<DataRow>();
		VariableType[] variableTypes = dataFields.getDataFieldArray();
		if (variableTypes != null){
			for (int i=0; i< variableTypes.length;i++){
				VariableType variableType = variableTypes[i];
				DataRow row = new DataRow();
				if (StringUtil.isNullOrEmpty(variableType.getDescription())){
					row.put("VAR_DESC",variableType.getCode());	
				}else{
					row.put("VAR_DESC",variableType.getDescription());					
				}
				row.put("VAR_CODE",variableType.getCode());
				row.put("VAR_TYPE",variableType.getDataType());
				row.put("VAR_INIT_VALUE",variableType.getInitialValue());
				result.add(row);
			}
		}
		return result;
	}
}
